//
//  ListTableViewController.swift
//  issac-note
//
//  Created by Issac on 16/8/27.
//  Copyright © 2016年 Issac. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class ListTableViewController: UITableViewController {
    
    //MARK: - Property
    @IBOutlet var noteCount: UIBarButtonItem!
    
    var index: Int?
    var toolbar: UIToolbar?
    var uid: String?
    var noteList: NSArray = []
    var refresh: Bool = false {
    
        didSet{
        
            if refresh {
            
                self.refreshControl?.beginRefreshing()
                self.refreshControl?.attributedTitle = NSAttributedString(string: "加载中...")
            
            }else {
            
                self.refreshControl?.endRefreshing()
                self.refreshControl?.attributedTitle = NSAttributedString(string: "下拉刷新")
            
            }
        
        }
    
    }

    //MARK: - ClassFunc
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if(self.uid == nil) {
        
            performSegueWithIdentifier("toLoginView", sender: nil)
            
        }else{
        
            self.tableView.showsVerticalScrollIndicator = false
            
            self.navigationController?.setToolbarHidden(false, animated: false)

            self.refreshControl = UIRefreshControl()
            self.refreshControl?.attributedTitle = NSAttributedString(string: "下拉刷新")
            self.refreshControl?.addTarget(self, action: #selector(refreshAction), forControlEvents: .ValueChanged)
            
            //清除多余行
            self.tableView.tableFooterView = UIView(frame: CGRectZero)
            
            getListDataFormServer()
        
        }
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        self.noteCount.title = String(self.noteList.count) + "个日志"
        
        return self.noteList.count
    
    }

    //设置cell
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
        
        if let data: NSDictionary = self.noteList[indexPath.row] as? NSDictionary {
        
            let title: UILabel = cell.viewWithTag(1) as! UILabel
            let date: UILabel = cell.viewWithTag(2) as! UILabel
            title.text = data["title"] as? String
            
            date.text = formatterTimeToDate(data["create_time"])
            
        
        }

        return cell
    }
    
    //将时间戳转为日期格式的时间
    func formatterTimeToDate(time: AnyObject?)->String {

        let timeStamp = time as! String
        let timeInterval: NSTimeInterval = NSTimeInterval(timeStamp)!
        let date = NSDate(timeIntervalSince1970: timeInterval)
        
        let dateformatter = NSDateFormatter()
        dateformatter.dateFormat = "yyyy/MM/dd"  //yyyy/MM/dd HH:mm:ss

        return dateformatter.stringFromDate(date)
        
    }
    
    //点击记录点击行号
    override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
        
        self.index = indexPath.row
        
        return indexPath
        
    }
    
    //点击
    override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
        
        return UITableViewCellEditingStyle.Delete
        
    }
    
    
    //设置删除按钮的text
    override func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? {
        return "删除日志"
    }
    
    //提交删除
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        
        if(editingStyle == UITableViewCellEditingStyle.Delete){
            
            let noteId = self.noteList[indexPath.row]["id"] as? String
            self.deleteNote(noteId!)
        
        }
    }
 
    //MARK: - myself-func
    func refreshAction(){
        
        self.refresh = true
        NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(refreshDelayAction), userInfo: nil, repeats: false)
    }
    
    func refreshDelayAction(){
    
        self.refresh = false
        self.getListDataFormServer()
        
    }
    
    internal func alertTipAction(message: String?){
    
        let alertAction = UIAlertController(title: "我的日志", message: message!, preferredStyle: .Alert)
        let cancelAction = UIAlertAction(title: "去写日志", style: .Cancel) { (sender) in
            
            self.performSegueWithIdentifier("toSetNoteView", sender: nil)
            
        }
        
        alertAction.addAction(cancelAction)
        self.presentViewController(alertAction, animated: true, completion: nil)
        
    }
    
    override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
        
        return identifier == "toLoginView" ?false :true
        
    }
    
    
    //MARK: - func-storyBoard
    @IBAction func editingCell(sender: UIBarButtonItem) {
        
        self.tableView.setEditing(!self.tableView.editing, animated: true)
        
        if self.tableView.editing {
        
            sender.title = "完成"
            
        }else {
        
            sender.title = "编辑"
        
        }
        
        
    }
    

    //MARK: - getDataFormServer
    func getListDataFormServer() {
    
        let url = "http://issac.website/issac-noteBackstage/Admin/Index/getNotesByUid?uid=1"
        let parameters = ["uid":self.uid!]
    
        
        Alamofire.request(.POST, url, parameters: parameters).responseJSON { (response) in
            
            switch response.result {
            
            case .Success:
                
                let json = JSON(response.result.value!)
                
                if(json["status"]) {
                
                    self.alertTipAction("暂无数据")
                    
                }else {
                
                    
                    self.noteList = json["data"].arrayObject! as NSArray
                
                    self.tableView.reloadData()
                
                }
                
            case .Failure:
                
                print("failure")
            
            }
            
        }
    
    }
    
    func deleteNote(noteId: String){
    
        let url = "http://issac.website/issac-noteBackstage/Admin/Index/deleteNote"
        let parameters = ["note_id" : noteId]
        
        Alamofire.request(.POST, url, parameters: parameters).responseJSON { (response) in
            
            switch response.result {
            
            case .Success:
                
                if let value = response.result.value {
                
                    let json = JSON(value)
                    if(!json["status"]) {
                    
                        self.getListDataFormServer()
                        
                    }else {
                    
                        print(json)
                        
                    }
                    
                }
                
            case .Failure:
                
                print("小心")
                
            }
            
        }
        
    }

    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        
        if segue.identifier == "toDetailView" {
            
            if let detailView: DetailViewController = segue.destinationViewController as? DetailViewController {
        
                let data = self.noteList[self.index!]
                
                detailView.noteTitle = data["title"] as? String
                detailView.noteContent = data["content"] as? String
                detailView.noteId = data["id"] as? String
                detailView.delegate = self
                
            }
            
        }else if segue.identifier == "toSetNoteView" {
        
            if let setNoteView: setNoteViewController = segue.destinationViewController as? setNoteViewController {
                
                setNoteView.uid = self.uid!
                setNoteView.delegate = self
                
            }
        
        }
        
    }
 
}


extension ListTableViewController: SendNoticeDelegate{
    
    func sendNotice(sender: Bool) {
        
        if sender {
        
            self.getListDataFormServer()
        
        }
        
    }
    
}
